//
//  WWStatusViewModel.swift
//  SinWEiBo
//
//  Created by 胡良志 on 2018/3/29.
//  Copyright © 2018年 HuLiangZhi. All rights reserved.
////  微博cell的视图模型,用来处理微博cell显示的数据

import UIKit
import YYText
class WWStatusViewModel: NSObject {

    //MARK:用户头像地址
    var iconURL : URL?
    //增加用户等级处理好的属性
    var mbRankImage : UIImage?
    //增加认证用户=处理好的属性
    var approveImage : UIImage?
    //正价处理好的微博来源
    var sourceText : String?
    
    
    //原创微博的字符属性(增加)
   @objc var originalAttributedString : NSMutableAttributedString?
    //转发微博的字符属性(增加)
   @objc var retWeetedAttributeString : NSMutableAttributedString?
    
    
    //处理好的原创和转发的图片地址
   @objc var imageURLs : [WWPictureInfo]?{
        if status?.retweeted_status == nil {
            return status?.pic_urls //原创微博
        }
        return status?.retweeted_status?.pic_urls //转发微博
    }
    
    //处理好的微博日期,在计算型属性中处理微博日期,当cell显示的时候会立即刷新时间
    var timeText : String?{
        //创建日期格式化对象
        let dateFormater = DateFormatter()
        //指定格式化符
        dateFormater.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
        //指定本地化信息(不然真机测试有问题 )
        dateFormater.locale = Locale(identifier: "en")
        //将字符串转换成日期对象
        guard let sinaDete = dateFormater.date(from: status?.created_at ?? "") else {return "穿越时空"}
//        print("-----\(sinaDete)")
        //处理日期
        //创建当前日历对象
        let calendar = Calendar.current
        //(通过与当前日期比较)
        let result = calendar.dateComponents([.year,.day], from: sinaDete, to: Date())
        //如果是今年
        if result.year == 0 {
            //今天
            if calendar.isDateInToday(sinaDete){
                //获取当前时间和sinaDate的差值
                let delta = Date().timeIntervalSince(sinaDete)
                if delta < 60{
                    return "刚刚"
                }else if delta < 3600{
                    return "\(Int( delta / 60))分钟前"
                }else{
                    return "\(Int( delta / 3600))小时前"
                }
            }else if calendar.isDateInYesterday(sinaDete) {
                //昨天
                //设置日期格式化符
                dateFormater.date(from: "昨天 HH:mm")
                return dateFormater.string(from: sinaDete)
            }else{
                //其他
                dateFormater.date(from: "MM-dd HH:mm")
                return dateFormater.string(from: sinaDete)
            }
        }else{
            //非今年
            dateFormater.dateFormat = "yyyy-MM-dd HH:mm"
            return dateFormater.string(from: sinaDete)
        }
    }
    
    
    
    var status : WWStatus?{
        didSet{
            //一旦外界赋值就在didSet中计算用户地址
            iconURL = URL(string: status?.user?.avatar_large ?? "")
            self.rank()
            self.approve()
          
            //因为来源不需要更新,所以直接赋值
            self.sourceText = WeiBoSource(source: status?.source ?? "")
            
            
            self.originalAttributedString = self.dealWeiboText(str: status?.text ?? "")
            self.retWeetedAttributeString = self.dealWeiboText(str: status?.retweeted_status?.text ?? "")
            self.originalAttributedString?.yy_font = UIFont.systemFont(ofSize: 15)
            self.retWeetedAttributeString?.yy_font = UIFont.systemFont(ofSize: 15)
        }
    }
    
    //将微博正文处理成富文本
    private func dealWeiboText(str : String) -> NSMutableAttributedString{
        
        //将str转换为可变的富文本
        let strM = NSMutableAttributedString(string: str)
        let pattern =  "#.*?#"
        //实例化正则表达式对象
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        //通过规则查找目标字符串
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count) )
    
      //倒序遍历,在处理表情字符串的时候会发生字节问题,表情图片占一位,字符串占四位
        for result in results.reversed() {
//            let range = result.range(at: 0)
//           let sub = (str as NSString).substring(with: range)
            //给字符添加文本属性
            
            strM.addAttributes( [NSAttributedStringKey.foregroundColor : UIColor.orange,NSAttributedStringKey.font : UIFont.systemFont(ofSize: 15)], range: result.range)
            
            let border = YYTextBorder(fill: UIColor.red, cornerRadius: 3)
            let highlight = YYTextHighlight()
            //高亮时文字的颜色
            highlight.setColor(UIColor.blue)
            highlight.setBackgroundBorder(border)
            //2. 把"高亮"属性设置到某个文本范围
            strM.yy_setTextHighlight(highlight, range: result.range)

        }
        addHighlighted(pattern: "@\\w+", strM: strM)
        addHighlighted(pattern: "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?", strM: strM)
        return strM
    }
    
    //处理 @某人 和 http
    private func addHighlighted (pattern:String,strM:NSMutableAttributedString){
        let str = strM.string
        //实例化正则表达式对象
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        //通过规则查找目标字符串
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count) )
        for result in results {
//            let range = result.range(at: 0)
            strM.addAttributes([NSAttributedStringKey.foregroundColor : UIColor.orange], range: result.range)
            //给特殊的文本添加点击事件  使用YYText
            /*
             YYTextBorder *border = [YYTextBorder borderWithFillColor:[UIColor grayColor] cornerRadius:3];
             YYTextHighlight *highlight = [YYTextHighlight new];
             [highlight setColor:[UIColor whiteColor]];
             [highlight setBackgroundBorder:highlightBorder];
             // 2. 把"高亮"属性设置到某个文本范围
             [attributedText yy_setTextHighlight:highlight range:highlightRange];
             */
            let border = YYTextBorder(fill: UIColor.red, cornerRadius: 3)
            let highlight = YYTextHighlight()
            //高亮时文字的颜色
            highlight.setColor(UIColor.blue)
            highlight.setBackgroundBorder(border)
            //2. 把"高亮"属性设置到某个文本范围
            strM.yy_setTextHighlight(highlight, range: result.range)

        }
    }
    
    
    //处理微博来源
    private func WeiBoSource (source : String) -> String{
 // "<a href=\"http://app.weibo.com/t/feed/4JpANe\" rel=\"nofollow\">微博搜索</a>"
        let startFlag = "\">"
        let endFlag = "</a>"
        guard let startRang = source.range(of: startFlag),
              let endRang = source.range(of: endFlag) else {return "来自火星"}
        
        let rang = startRang.upperBound ..< endRang.lowerBound
        
        return  source.substring(with: rang)
    }
    
    //处理用户等级
    private func rank (){
        let rank = status?.user?.mbrank ?? 0
        if rank > 0 && rank < 7 {
            mbRankImage = UIImage(named: "common_icon_membership_level\(rank)")
        }
        
    }
    //处理认证用户
    private func approve(){
        let type = status?.user?.verified_type ?? -1
        //判断type
        switch type {
        case 0:
            approveImage = #imageLiteral(resourceName: "avatar_vip")
        case 2,3,5:
            approveImage = #imageLiteral(resourceName: "avatar_enterprise_vip")
        case 220:
            approveImage = #imageLiteral(resourceName: "avatar_grassroot")
        default:
            approveImage = nil
        }
    }
    
    
    
    
}















